package com.maven.util;


import com.maven.entity.UserInfo;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wmh
 * @version 1.0 2022/7/3
 * @Description: 校验
 **/
public class ValidationUtil {
    //线程安全的：所有的方法都可以使用这个对象，而不会产生线程安全的问题
    private static Validator validator;
    private static Validator validFailFast;
    private static ExecutableValidator executables;
    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
        //快速失败
        validFailFast = Validation.byProvider(HibernateValidator.class).configure()
                //配置快速失败
                .failFast(true).buildValidatorFactory().getValidator();
        //校验入参或返回值的
        executables = validator.forExecutables();
    }
    public static<T> List<String> validNotBean(T object, Method method, Object[] parameterValues, Class<?>... groups){
        Set<ConstraintViolation<T>> set = executables.validateParameters(object, method, parameterValues, groups);
        List<String> list = set.stream().map(v -> "属性：" + v.getPropertyPath() + "，属性值是：" + v.getInvalidValue()
                + "，校验不通过的提示信息：" + v.getMessage()+"，消息模板："+v.getMessageTemplate()).collect(Collectors.toList());
        return list;
    }

    public static List<String> validFailFast(UserInfo userInfo,Class<?>... groups){
        //如果被校验对象userInfo没有检验通过，则2set里面就有校验信息，返回出去
        Set<ConstraintViolation<UserInfo>> set = validator.validate(userInfo,groups);
        List<String> list = set.stream().map(v -> "属性：" + v.getPropertyPath() + "，属性值是：" + v.getInvalidValue()
                + "，校验不通过的提示信息：" + v.getMessage()+"，消息模板："+v.getMessageTemplate()).collect(Collectors.toList());
        return list;
    }

    //校验，要检验的对象，检验分组
    public static List<String> valid(UserInfo userInfo,Class<?>... groups){
        //如果被校验对象userInfo没有检验通过，则2set里面就有校验信息，返回出去
        Set<ConstraintViolation<UserInfo>> set = validator.validate(userInfo,groups);
        List<String> list = set.stream().map(v -> "属性：" + v.getPropertyPath() + "，属性值是：" + v.getInvalidValue()
                + "，校验不通过的提示信息：" + v.getMessage()+"，消息模板："+v.getMessageTemplate()).collect(Collectors.toList());
        return list;
    }
}